package com.mm.fam.web.netty.vo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 解码
 */
@Slf4j
public class Decoder extends ByteToMessageDecoder {

    /**
     * <pre>
     * 协议开始的标准head_data，int类型，占据4个字节.
     * 表示数据的长度contentLength，int类型，占据4个字节.
     * </pre>
     */
    public final int BASE_LENGTH = 0;

    private ByteBuf delimiter;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {

//        if (buffer.readableBytes() < BASE_LENGTH) {
//            return;
//        }
//        buffer.markReaderIndex();
//        byte encode = buffer.readByte();
//        byte encrypt = buffer.readByte();
//        byte extend1 = buffer.readByte();
//        byte extend2 = buffer.readByte();
//        int sessionid = buffer.readInt();
//        int result = buffer.readInt();
//        int length = buffer.readInt(); // 数据包长
//        log.error(byteToString(encode));
//        log.error(byteToString(encrypt));
//        log.error(byteToString(extend1));

//        XLResponse response = new XLResponse();
//        response.setEncode(encode);
//        response.setEncrypt(encrypt);
//        response.setExtend1(extend1);
//        response.setExtend2(extend2);
//        response.setSessionid(sessionid);
//        response.setResult(result);
//        response.setLength(length);

//        response.setValues(ProtocolUtil.decode(encode, dataBuffer));
//        response.setIp(ProtocolUtil.getClientIp(channel));
//        return response;

        log.error("-----1--{}",buffer.readableBytes());
        // 可读长度必须大于基本长度
        if (buffer.readableBytes() >= BASE_LENGTH) {
            // 防止socket字节流攻击
            // 防止，客户端传来的数据过大
            // 因为，太大的数据，是不合理的
            if (buffer.readableBytes() > 2048) {
                buffer.skipBytes(buffer.readableBytes());
            }

            // 记录包头开始的index
            int beginReader;

            while (true) {
                // 获取包头开始的index
                beginReader = buffer.readerIndex();
                // 标记包头开始的index
                buffer.markReaderIndex();
                // 读到了协议的开始标志，结束while循环

                log.error("-----2---------{}",buffer.readInt());
                if (buffer.readInt() == 0X76) {
                    break;
                }

                // 未读到包头，略过一个字节
                // 每次略过，一个字节，去读取，包头信息的开始标记
                buffer.resetReaderIndex();
                buffer.readByte();

                // 当略过，一个字节之后，
                // 数据包的长度，又变得不满足
                // 此时，应该结束。等待后面的数据到达
                if (buffer.readableBytes() < BASE_LENGTH) {
                    return;
                }
            }

            // 消息的长度

            int length = buffer.readInt();
            // 判断请求数据包数据是否到齐
            if (buffer.readableBytes() < length) {
                // 还原读指针
                buffer.readerIndex(beginReader);
                return;
            }

            // 读取data数据
            byte[] data = new byte[length];
            buffer.readBytes(data);

            Protocol protocol = new Protocol(data.length, data);
            out.add(protocol);
        }
    }

    private static int indexOf(ByteBuf haystack, ByteBuf needle) {
        int length = 0;
        for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++, length++) {
            if (length >= 9 && haystack.getByte(i) == needle.getByte(0)) {
                return i - haystack.readerIndex();
            }
        }
        return -1;
    }


    private static String byteToString(byte req) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sTemp = new StringBuffer();
        sTemp.append(Integer.toHexString(0xFF & req).toUpperCase());
        if (sTemp.length() < 2)
            sb.append("0");
        sb.append(sTemp);
        return sb.toString();
    }

    private static String eqNumberFromByte(byte[] req, int a, int b) {
        StringBuffer sb = new StringBuffer();
        for (int i = a; i < b; i++) {
            StringBuffer sTemp = new StringBuffer();
            sTemp.append(Integer.toHexString(0xFF & req[i]).toUpperCase());
            if (sTemp.length() < 2)
                sb.append("0");
            sb.append(sTemp);
        }
        return sb.toString();
    }


    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        log.error(bytesToHex(new byte[]{22}));
    }
}
